import requests
import re
import datetime
from email.mime.text import MIMEText
from email.header import Header
import smtplib
import time
import logging


def send_mail(subject='小说更新提醒', content='《重生之都市仙尊》刚刚更新了', receiver=['1206143866@qq.com'],
              text_or_html='plain',     # html发送HTML邮件，plain发送纯文本邮件
              from_address='发送者email',
              password='发送者email的smtp授权码',
              smtp_server='smtp.qq.com',
              smtp_port=465):

    msg = MIMEText(content, text_or_html, 'utf-8')
    msg['From'] = Header(from_address)
    msg['Subject'] = subject
    send_email = smtplib.SMTP_SSL(host=smtp_server, port=smtp_port)  # 使用SMTP而不是SMTP_SSL QQ邮箱25端口在Windows本机上可以发邮件，但部署到阿里云就超时
    send_email.login(from_address, password)
    send_email.sendmail(from_address, receiver, msg.as_string())
    send_email.quit()  # 关闭连接


def get_html_page(url):
    response = requests.get(url=url, headers=None)
    return response.text


def is_update(html):
    update_date = str(re.search('(\d{4}-\d{2}-\d{2})', html).group(1))
    today = str(datetime.date.today())
    return update_date == today


def main_old():
    urls = ['http://m.yaotabook.com/xs/19960/', 'https://www.biqiuge.com/book/36242/']
    while True:
        now_hours = int(time.strftime("%H"))
        if (now_hours > 10) and (now_hours < 22):
            
            flag = False
            try:
                html = get_html_page(urls[0])
            except Exception as e:
                msg = '抓取过程出现异常：' + str(e)
                print_log(msg)
                continue
            else:
                flag = is_update(html)
            
            if flag:
                print_log('有更新，开始发送邮件')
                try:
                    send_mail()
                except Exception as e:
                    msg = '发送邮件时出现异常：' + str(e)
                    print_log(msg)
                    time.sleep(60)
                    continue
                else:
                    print_log('邮件发送完成，12小时后再检测')
                    time.sleep(12 * 60 * 60)  # 每次发送更新邮件后休眠12小时，等第二天再检测
            else:
                print_log('没有更新，5分钟后再检测')
                time.sleep(5 * 60)  # 每天12点后5分词检测一次
        else:
            time.sleep(30 * 60)  # 每天中午12点前一次休眠30分钟


def print_log(msg):
    logging.error(time.strftime("[%Y-%m-%d %H:%M:%S] ") + msg)


if __name__ == '__main__':
    main_old()
